package com.example.leetcode.trainingcamp.week1.practice2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 编写一种算法，若M × N矩阵中某个元素为0，则将其所在的行与列清零。
 */
public class Offer01_08 {


    public void setZeroes(int[][] matrix) {
        int row = matrix.length;
        int column = matrix[0].length;
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i =0;i<row;i++){
            for (int j=0;j<column;j++){
                if (matrix[i][j] == 0){
                    if (map.containsKey(i)){
                        List<Integer> list = map.get(i);
                        list.add(j);
                    }else {
                        List<Integer> list = new ArrayList<>();
                        list.add(j);
                        map.put(i,list);
                    }
                }
            }
        }
        for (Map.Entry<Integer,List<Integer>>entry:map.entrySet()) {
            Integer key = entry.getKey();
            for (int i = 0;i<column;i++){
                matrix[key][i] = 0;
            }
            List<Integer> list = entry.getValue();
            for (int c:list) {
                for (int j = 0;j<row;j++){
                    matrix[j][c] = 0;
                }
            }
        }
    }
}
